Testing equality of an enum value with equals
is perfectly valid because an enum is an Object and every Java developer knows "=="
should not be used to compare the content of an Object. At the same time, using "==" on enums:
- provides the same expected comparison (content) as
equals
- is more null-safe than equals()
- provides compile-time (static) checking rather than runtime checking
For these reasons, use of "==" should be preferred to equals
.
Noncompliant code example
public enum Fruit {
APPLE, BANANA, GRAPE
}
public enum Cake {
LEMON_TART, CHEESE_CAKE
}
public boolean isFruitGrape(Fruit candidateFruit) {
return candidateFruit.equals(Fruit.GRAPE); // Noncompliant; this will raise an NPE if candidateFruit is NULL
}
public boolean isFruitGrape(Cake candidateFruit) {
return candidateFruit.equals(Fruit.GRAPE); // Noncompliant; always returns false
}
Compliant solution
public boolean isFruitGrape(Fruit candidateFruit) {
return candidateFruit == Fruit.GRAPE; // Compliant; there is only one instance of Fruit.GRAPE - if candidateFruit is a GRAPE it will have the same reference as Fruit.GRAPE
}
public boolean isFruitGrape(Cake candidateFruit) {
return candidateFruit == Fruit.GRAPE; // Compliant; compilation time failure
}